﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.Diagnostics.Internal;
using Microsoft.WindowsAzure.Diagnostics.Management;

using Ciripescu_WebRole.Entities;
using Ciripescu_WebRole.BL;
using System.Net;
using System.Drawing;
using System.IO;
namespace Ciripescu_WebRole
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;

            // Attempt to peform first request initialization
            FirstRequestInitialization.Initialize(context);

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            System.Web.HttpContext context = HttpContext.Current;
            System.Exception ex = Context.Server.GetLastError();

            if (ex == null)
            {                
                context.Server.ClearError();                
                //RoleManager.WriteToLog("Critical","S-a ajuns in global.asax la Application_Error dar GetLastError() a returnat null!");
                Utils.WriteLog(EventLogName.Error, "Error at global.asax at Application_Error, but GetLastError() returned null!");

                ShowError.ShowErrorMessage("Internal error occured!", context);
                return;

            }
            string ex_name = ex.GetType().ToString();
            
                context.Server.ClearError();
                string log = "\nMESSAGE: " + ex.Message + "\nSOURCE: " + ex.Source + "\nFORM: " + context.Request.Form.ToString() + "\nQUERYSTRING: " + context.Request.QueryString.ToString() + "\nTARGETSITE: " + ex.TargetSite + "\nSTACKTRACE: " + ex.StackTrace;
                //RoleManager.WriteToLog("Critical", "Eroare prinsa in global.asax: \r\n" + log);
                Utils.WriteLog(EventLogName.Error, "Exception catch in global.asax: \r\n" + log);   
            ShowError.ShowErrorMessage("Internal error occured!",context);
            //ShowError.ShowErrorMessage("Eroare prinsa in global.asax: \r\n" + log, context);                
            
            
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }


    }
    public class FirstRequestInitialization
    {
        private static bool s_InitializedAlready = false;
        private static Object s_lock = new Object();


        // Initialize only on the first request
        public static void Initialize(HttpContext context)
        {
            if (s_InitializedAlready)
            {
                return;
            }

            lock (s_lock)
            {
                if (s_InitializedAlready)
                {
                    return;
                }

                //ApplicationStartUponFirstRequest(context);
                ApplicationStartUponFirstRequest();
                s_InitializedAlready = true;
            }
        }

        
        //public static void ApplicationStartUponFirstRequest(HttpContext context)
        public static void ApplicationStartUponFirstRequest()
        {
            // This is where you put initialization logic for the site.
            // RoleManager is properly initialized at this point.

            // Create the tables on first request initialization as there is a performance impact
            // if you call CreateTablesFromModel() when the tables already exist. This limits the exposure of
            // creating tables multiple times.
            
            // Table creation was needed before Azure SDK nov 2009 release. Starting with this build tables are build automatically 
            // by windows azure, so this code is not needed. I let it in this form because I need it so for some test purposes.
            
            // Get the settings from the Service Configuration file
            MyServiceContext svContext = new MyServiceContext();
            StorageAccountInfo account = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();
            account.CheckComplete();
            //RoleManager.WriteToLog(EventLogName.Information.ToString(), "Acount name(1):" + account.AccountName);
           // RoleManager.WriteToLog(EventLogName.Information.ToString(), "Is complete setting(1):" + account.IsCompleteSetting());
            //RoleManager.WriteToLog(EventLogName.Information.ToString(), "Base Uri(1): " + account.BaseUri);
            
            // Create the tables           
            // This will create tables for all public properties that are IQueryable (collections)
            try
            {
                TableStorage ts = TableStorage.Create(account);
                if (!ts.DoesTableExist(svContext.UsersTableName))
                {
                    //RoleManager.WriteToLog(EventLogName.Information.ToString(), "Start creating users table...");
                    ts.CreateTable(svContext.UsersTableName);
                    //RoleManager.WriteToLog(EventLogName.Information.ToString(), "After creating users table...exists value: " +
                    //ts.DoesTableExist(svContext.UsersTableName).ToString());
                }
                if (!ts.DoesTableExist(svContext.CiripTableName))
                    ts.CreateTable(svContext.CiripTableName);
                if (!ts.DoesTableExist(svContext.CiripMessageTableName))
                    ts.CreateTable(svContext.CiripMessageTableName);
                if (!ts.DoesTableExist(svContext.InviteTableName))
                    ts.CreateTable(svContext.InviteTableName);
                if (!ts.DoesTableExist(svContext.FollowersTableName))
                    ts.CreateTable(svContext.FollowersTableName);
                if (!ts.DoesTableExist(svContext.CiripCacheTableName))
                    ts.CreateTable(svContext.CiripCacheTableName);
                if (!ts.DoesTableExist(svContext.VoturiTableName))
                    ts.CreateTable(svContext.VoturiTableName);
                if (!ts.DoesTableExist(svContext.CommentTableName))
                    ts.CreateTable(svContext.CommentTableName);

                //TableStorage.CreateTablesFromModel(typeof(User), account);
                //TableStorage.CreateTablesFromModel(typeof(Cirip), account);
                //TableStorage.CreateTablesFromModel(typeof(Urmarire), account);
                //TableStorage.CreateTablesFromModel(typeof(Invite), account);
                //TableStorage.CreateTablesFromModel(typeof(CiripMessage), account);
                  
                // Uri baseUri        = new Uri(RoleManager.GetConfigurationSetting("QueueEndpoint"));
                // string accountName = RoleManager.GetConfigurationSetting("AccountName");
                // string accountKey  = RoleManager.GetConfigurationSetting("AccountSharedKey");

                //StorageAccountInfo qAccount = new StorageAccountInfo(baseUri,
                //                                                     null,
                //                                                     accountName,
                //                                                     accountKey);
                StorageAccountInfo qAccount = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();
                QueueStorage service = QueueStorage.Create(qAccount);
                MessageQueue queue = service.GetQueue(MailQueue.ScheduledQueueName);
                MessageQueue urgent = service.GetQueue(MailQueue.UrgentQueueName);

                if (!queue.DoesQueueExist())
                {
                    queue.CreateQueue();
                }

                if (!urgent.DoesQueueExist())
                {
                    urgent.CreateQueue();
                }

                BlobStorage blobStorage = BlobStorage.Create(StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration());
                BlobContainer blobCntainer = blobStorage.GetBlobContainer("ciripescucontainer");//container name 
                if (!blobCntainer.DoesContainerExist())
                    blobCntainer.CreateContainer(null, ContainerAccessControl.Public);

                
            }
            catch (Exception ex)
            {
                Utils.WriteLog(EventLogName.Error, "Could not create default table and queue storage." + ex.ToString());
                //RoleManager.WriteToLog("Critical", "Could not create default table and queue storage." + ex.ToString());
            }
            //create default picture Uri/save picture if it does not exist

            
            // Create the requests.
            //try
            //{

            //    // fa un user de admin:
            //    UserManager um = new UserManager();
            //    User u = um.GetItem("admin");
            //    if (u == null)
            //    {
            //        u = new User("admin", "admin", "starcraft", "contact@bitstarsolutions.com", "localghost");
            //        u.Group = (int)UserGroup.Admin;
            //        um.Insert(u);
            //    }
            //    else
            //    {
            //        u.Group = (int)UserGroup.Admin;
            //        um.Save(u);
            //    }

            //    WebRequest requestPic   = WebRequest.Create(Ciripescu_WebRole.Properties.Settings.Default.DefaultPicDownloadUrl);
            //    WebResponse responsePic = requestPic.GetResponse();

            //    Image webImage  = Image.FromStream(responsePic.GetResponseStream());
            //    CBlobStorage b  = new CBlobStorage();
            //    MemoryStream ms = new MemoryStream();
            //    webImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                
            //    b.SaveImage(Properties.Settings.Default.DefaultPictureId, 
            //                System.Drawing.Imaging.ImageFormat.Png.ToString(), 
            //                ms.ToArray());
            //}
            //catch(Exception ex)
            //{
            //    Utils.WriteLog(EventLogName.Error, "Could not create default picture uri.Default picture not saved." + ex.ToString());
            //    //RoleManager.WriteToLog("Critical","Could not create default picture uri.Default picture not saved."+ex.ToString());
            //}
        }
    }
}